/**
 * 
 */
package pl.com.qapps.datastore.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import pl.com.qapps.datastore.EntityStore;
import pl.com.qapps.datastore.IdStore;
import pl.com.qapps.datastore.KindIndex;
import pl.com.qapps.datastore.Store;

import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;

/**
 * Controls the underlying Datastore.
 * 
 * @author Jakub Dykowski
 * 
 */
public class DatastoreController {

	protected Store store;

	public DatastoreController(Store datastore) {
		this.store = Objects.requireNonNull(datastore,
				"datastore cannot be null");
	}

	public QueryResult queryByKind(String kind, FetchOptions opts) {
		KindIndex index = store.getKindIndex();

		throw new UnsupportedOperationException("not supported yet");
	}

	/**
	 * Can be null if it is root entity
	 * 
	 * @param parent
	 */
	public long allocateIds(Key parent, long amount) {
		IdStore idStore = store.getIdStore();
		try {
			return idStore.next(parent, amount);
		} catch (IOException e) {
			throw new DatastoreFailureException(e.getMessage());
		}
	}

	private List<Key> loadKeys(KeySource source) {
		List<Key> keys = new LinkedList<Key>();
		Key fetchedKey = null;
		while ((fetchedKey = source.next()) != null) {
			keys.add(fetchedKey);
		}
		return keys;
	}
}
